package com.dhh.sky.activity;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import net.londatiga.android.ActionItem;
import net.londatiga.android.QuickAction;

import com.dhh.sky.R;
import com.dhh.sky.util.FileUtil;
import com.korovyansk.android.slideout.SlideoutActivity;
import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.ActionBar.Action;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.MimeTypeMap;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class FileViewActivity extends ListActivity {
	private ImageLoader imageLoader = ImageLoader.getInstance();
    private DisplayImageOptions options;
	
	private class FilePickerListAdapter extends BaseAdapter {
        private final LayoutInflater mInflater;
        private final ArrayList<File> mFiles;
        private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

        public FilePickerListAdapter(Context context) {
            mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            mFiles = new ArrayList<File>();
        }

        public ArrayList<File> getFiles() {
            return mFiles;
        }

        @Override
        public int getCount() {
            return mFiles.size();
        }

        @Override
        public File getItem(int position) {
            return mFiles.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v = convertView != null ? convertView :
                                           mInflater.inflate(R.layout.file_list_item,
                                                             parent,
                                                             false);
            Button icon = (Button) v.findViewById(R.id.fli_icon);
            TextView name = (TextView) v.findViewById(R.id.fli_title);
            TextView date = (TextView) v.findViewById(R.id.fli_date);
            TextView size = (TextView) v.findViewById(R.id.fli_size);
            v.findViewById(R.id.fli_more).setVisibility(View.GONE);

            final File file = getItem(position);
            name.setText(file.getName());
            Date mDate = new Date();
            mDate.setTime(file.lastModified());
            date.setText(format.format(mDate));
            if(file.isDirectory()){
            	icon.setBackgroundResource(R.drawable.ic_folder);
            	icon.setVisibility(View.VISIBLE);
        		v.findViewById(R.id.fli_img).setVisibility(View.GONE);
            }else{
            	String ext = FileUtil.getFileExt(file.getName());
        		v.findViewById(R.id.fli_img).setVisibility(View.GONE);
        		icon.setVisibility(View.VISIBLE);
        		icon.setBackgroundResource(R.drawable.ic_file_w);
            	if(FileUtil.audioType.contains(ext)){
                	icon.setBackgroundResource(R.drawable.ic_audio);
            	}else if(FileUtil.vedioType.contains(ext)){
                	icon.setBackgroundResource(R.drawable.ic_vedio);
            	}else if(FileUtil.imgType.contains(ext)){
            		icon.setVisibility(View.GONE);
    				ImageView img = (ImageView) v.findViewById(R.id.fli_img);
    				imageLoader.displayImage("file:///"+file.getAbsolutePath(), img, options);
    				img.setVisibility(View.VISIBLE);    				
            	}else if(FileUtil.docType.contains(ext)){
                	icon.setBackgroundResource(R.drawable.ic_doc);
            	}else if(FileUtil.excelType.contains(ext)){
                	icon.setBackgroundResource(R.drawable.ic_excel);
            	}else if(FileUtil.powPointType.contains(ext)){
                	icon.setBackgroundResource(R.drawable.ic_pps);
            	}else if(FileUtil.pdfType.contains(ext)){
                	icon.setBackgroundResource(R.drawable.ic_pdf);
            	}else if(FileUtil.zipType.contains(ext)){
                	icon.setBackgroundResource(R.drawable.ic_zip);
            	}else{
            		icon.setBackgroundResource(R.drawable.ic_file_w);
            	}
            }
            
            String sVal = "";
            if(!file.isDirectory()){
            	sVal = "1 KB";
                if(file.length()/1024 > 1){
                	sVal = (file.length()/1024) + " KB";
                }
                
            }
            size.setText(sVal);

            
            final Button bMore = (Button) v.findViewById(R.id.fli_more);
            LinearLayout moreLst = (LinearLayout) v.findViewById(R.id.fli_more_lst);
            View.OnClickListener listener = new View.OnClickListener(){
				@Override
				public void onClick(View v) {
					final int op_open = 1;
					final int op_delelte = 2;
					QuickAction quickAction = new QuickAction(FileViewActivity.this);	
					ActionItem openItem     = new ActionItem(op_open, "Open", getResources().getDrawable(R.drawable.ic_open));
					quickAction.addActionItem(openItem);
					ActionItem deleteItem     = new ActionItem(op_delelte, "Delete", getResources().getDrawable(R.drawable.ic_delete));
					quickAction.addActionItem(deleteItem);
					
					quickAction.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener(){
						@Override
						public void onItemClick(QuickAction source, int pos, int actionId) {
							if(actionId == op_open){
								Intent intent = new Intent();
		                        intent.setAction(android.content.Intent.ACTION_VIEW);                   
		                        MimeTypeMap mime = MimeTypeMap.getSingleton();
		                        String ext= file.getName().substring(file.getName().indexOf(".")+1);
		                        if(ext!=null)
		                        	ext = ext.toLowerCase();
		                        String type = mime.getMimeTypeFromExtension(ext);                  
		                        intent.setDataAndType(Uri.fromFile(file),type);                   
		                        startActivity(intent);
							}else if(actionId == op_delelte){
								file.delete();
								for(File f : mFiles){
									if(f.getName().equals(file.getName())){
										mFiles.remove(f);
										break;
									}
								}
								handler.sendEmptyMessage(0);
							}
						}
					});
					
					quickAction.show(bMore);
				}
			};
            
        	bMore.setVisibility(View.VISIBLE);
        	bMore.setOnClickListener(listener);
        	moreLst.setOnClickListener(listener);
        	
            return v;
        }
    }
    public static final int PICK_FILE_REQUEST = 0;
    public static final String EXTRA_FILE_PATH = "filePath";
    private FilePickerListAdapter mAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.download_file);
        initActionBar();
		imageLoader.init(ImageLoaderConfiguration.createDefault(this));
		options = new DisplayImageOptions.Builder()
					.showStubImage(R.drawable.stub_image)
					.showImageForEmptyUrl(R.drawable.image_for_empty_url)
					.cacheInMemory()
					.cacheOnDisc()
					.build();
        ListView lv = getListView();
        lv.setTextFilterEnabled(true);
        lv.setDivider( null );
		lv.setDividerHeight(0); 
		lv.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                File file = (File) parent.getItemAtPosition(position);

                if (!file.isDirectory()) {
                	try{
                		Intent intent = new Intent();
                        intent.setAction(android.content.Intent.ACTION_VIEW);                   
                        MimeTypeMap mime = MimeTypeMap.getSingleton();
                        String ext= getFileExt(file.getName());
                        String type = mime.getMimeTypeFromExtension(ext);                  
                        intent.setDataAndType(Uri.fromFile(file),type);                   
                        startActivity(intent);
                	}catch(Exception e){
                		Toast.makeText(FileViewActivity.this, getString(R.string.msg_open_fail), Toast.LENGTH_LONG).show();
                	}
                } 
            }
        });
        mAdapter = new FilePickerListAdapter(FileViewActivity.this);
        
        setListAdapter(mAdapter);
    }
    
    private void initActionBar(){
    	ActionBar actionBar = (ActionBar) findViewById(R.id.actionbar);
		actionBar.setHomeAction(new HomeAction());
		actionBar.setTitle(getString(R.string.title_download_file));
	}
    
    private class HomeAction implements Action {
	    @Override
	    public int getDrawable() {
	        return R.drawable.ic_home_arrow;
	    }

	    @Override
	    public void performAction(View view) {	    	
	    	int width = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 40, getResources().getDisplayMetrics());
			SlideoutActivity.prepare(FileViewActivity.this, R.id.inner_content, width);
			startActivity(new Intent(FileViewActivity.this,MenuActivity.class));
			overridePendingTransition(0, 0);
	    }

	}

    @Override
    protected void onStart() {
        super.onStart();
		String director = Environment.getExternalStorageDirectory().getPath();
        File file = new File(director+"/SkyDrive");
        
        if(!file.exists())
        	file.mkdir();
        loadFolder(file);
    }

    private void loadFolder(File folder) {
        assert folder.isDirectory();
        setTitle(folder.getName());

        ProgressDialog progressDialog = ProgressDialog.show(this, "", getString(R.string.msg_loading), true);
        ArrayList<File> adapterFiles = mAdapter.getFiles();
        adapterFiles.clear();
        for(File file : folder.listFiles()){
        	if(file.isDirectory()){
        		adapterFiles.add(file);
        	}else{
        		adapterFiles.add(file);    		
        	}
        }
        
        mAdapter.notifyDataSetChanged();
        progressDialog.dismiss();
    }
    
    private String getFileExt(String name){		
		int sp = name.lastIndexOf(".");
		String ext = "";
		if(sp>=0){
			ext = name.substring(sp+1,name.length());
		}
		
		return ext.toLowerCase();
	}
    
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {  
        	mAdapter.notifyDataSetChanged();
        }
    };
}
